package com.hzdesk.media.koreabatchmatvector.logic.persenter;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.hzdesk.media.koreabatchmatvector.R;
import com.hzdesk.media.koreabatchmatvector.adapter.MyVideoListAdapter;
import com.hzdesk.media.koreabatchmatvector.base.MyClientApplication;
import com.hzdesk.media.koreabatchmatvector.bean.UploadBean;
import com.hzdesk.media.koreabatchmatvector.bean.UploadFileTokenBean;
import com.hzdesk.media.koreabatchmatvector.bean.VideoFile;
import com.hzdesk.media.koreabatchmatvector.config.AppConfig;
import com.hzdesk.media.koreabatchmatvector.config.RBConfig;
import com.hzdesk.media.koreabatchmatvector.config.RxBusUtil;
import com.hzdesk.media.koreabatchmatvector.dao.VideoFileDaoUtils;
import com.hzdesk.media.koreabatchmatvector.dialog.DeleteFileDialog;
import com.hzdesk.media.koreabatchmatvector.inter.IDeleteFileDialogListener;
import com.hzdesk.media.koreabatchmatvector.inter.OnItemClickListener;
import com.hzdesk.media.koreabatchmatvector.logic.contract.VideoListContract;
import com.hzdesk.media.koreabatchmatvector.logic.model.VideoListModle;
import com.hzdesk.media.koreabatchmatvector.request.RequestAction;
import com.hzdesk.media.koreabatchmatvector.request.UploadFileRequest;
import com.hzdesk.media.koreabatchmatvector.request.UploadImageRequest;
import com.hzdesk.media.koreabatchmatvector.service.UpLoadFileService;
import com.hzdesk.media.koreabatchmatvector.utils.DeleteDirTest;
import com.hzdesk.media.koreabatchmatvector.utils.MyToastUtils;
import com.hzdesk.media.koreabatchmatvector.utils.RxBus;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Administrator on 2018/7/10.
 * 杭州席媒科技有限公司  Developers  刘传华  10
 * 佛祖镇楼 bug辟易
 */

public class VideoListPersenter implements VideoListContract.IVideoListPersenter {
    private String TAG="VideoListModle";

    private VideoListContract.IVideoListView mIVideoListView;
    private VideoListContract.IVideoListModle iVideoListModle;
    private VideoFileDaoUtils videoFileDaoUtils;
    private List<VideoFile> list;
    private MyVideoListAdapter mMyVideoListAdapter;
    private String uuid;

    private RecyclerView mRecyclerView;
    private Context mContext;
    private boolean flag = true;
    private boolean isUpload=false;
    private UploadFileRequest uploadFileRequest;
    private UploadImageRequest uploadImageRequest;
    private UpLoadFileService.UploadBinder uploadBinder;
    private UploadBean uploadBean;
    private UploadFileTokenBean TokenBean;
    private VideoFile current_videoFile;
    private int position;
    private DeleteFileDialog deleteFileDialog;
    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int num=msg.arg1;
            //textview_progress.setText(num+"%");
            VideoFile bean = list.get(position);
            bean.setProgress(num);
            bean.setIsUpload(true);
            list.set(position,bean);
            Log.e(TAG,"刷新："+position);
            //mProgressBar.setProgress(num);
            mMyVideoListAdapter.notifyDataSetChanged();
        }
    };
    public VideoListPersenter(VideoListContract.IVideoListView mIVideoListView) {
        this.mIVideoListView = mIVideoListView;
        this.iVideoListModle=new VideoListModle();
    }

    @Override
    public void initDate(Context tContext, RecyclerView tRecyclerView,Intent intent) {
        uuid=intent.getStringExtra("uuid");
        mRecyclerView = tRecyclerView;
        mContext = tContext;

        //  获取数据库数据 并内存使用情况计算出进度
        getlocalVideo(mContext);
        //  获取数据库视频路径数据并排序
        getVideoFile();
        setItemClickListener();
        setListener();

        uploadFileRequest=new UploadFileRequest(tContext, RBConfig.HOST_IP+ RequestAction.getUploadfile());
    }
    private void getVideoFile() {
        list = videoFileDaoUtils.queryVideoFileByUUID(uuid);
        Collections.sort(list,new VideoFileComparator());
        //  对是视频的一系列操作在Adapter中进行 -------------------->这个适配器要改里面的逻辑太复杂
        LinearLayoutManager layoutmanager = new LinearLayoutManager(mContext);
        layoutmanager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutmanager);
        mMyVideoListAdapter = new MyVideoListAdapter(mContext);
        mRecyclerView.setAdapter(mMyVideoListAdapter);
        mMyVideoListAdapter.addItemDate(list);
        mMyVideoListAdapter.changeState(2);

    }

    private void getlocalVideo(Context mContext) {
        int   progress = 0;
        videoFileDaoUtils = new VideoFileDaoUtils(mContext);
        List<VideoFile> bean =  videoFileDaoUtils.queryAllVideoFile();
        long filesize = 0;
        for (VideoFile videoFile : bean) {
            filesize = filesize+videoFile.getSize();
        }
        long UnitConversion = AppConfig.LOCAL_CAPACITITY*1024 - filesize/1024 ;
        if(UnitConversion >1024){
            mIVideoListView.setStorageMessage(mContext.getString(R.string.surplus)+UnitConversion/1024+"GB");

        }else{
            mIVideoListView.setStorageMessage(mContext.getString(R.string.surplus)+UnitConversion+"MB");
        }
        if (UnitConversion>0){
            progress= (int) (((filesize/1024)/(AppConfig.LOCAL_CAPACITITY*1024))*100);
        }
        mIVideoListView.setLoclProgress(progress);
    }


    private void setItemClickListener() {
        mMyVideoListAdapter.setmOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemPlay(VideoFile mVideoFile) {
                String path = mVideoFile.getPath()+"/"+mVideoFile.getSecondname()+AppConfig.FILE_TYPE_MP4;
                // Log.e("VideoListModle", "onItemPlay 2222: "+path );
                MyClientApplication.setVideoFile(mVideoFile);
                mIVideoListView.toVideoPlayerPager(path);
            }
            @Override
            public void onItemDelete(VideoFile removeFile) {
                showDialog( removeFile, mContext);
            }

            @Override
            public void onItemUpload(VideoFile videoFile,int p) {
                //上传
                uploadFile(videoFile,p);
            }
        });
    }
    private void showDialog(final VideoFile removeFile, Context mContext){
        deleteFileDialog = new DeleteFileDialog(mContext,removeFile.getName(),mContext.getString(R.string.delete_file));
        deleteFileDialog.show();
        deleteFileDialog.setmIDeleteFileDialogListener(new IDeleteFileDialogListener() {
            @Override
            public void cancel() {
                deleteFileDialog.dismiss();
            }

            @Override
            public void confirm() {
                // 清空容器
                list.clear();
                mMyVideoListAdapter.notifyDataSetChanged();
                // 数据库删除对应的数据
                long id =  removeFile.getId();
                boolean flag =  videoFileDaoUtils.clearId(id);
                if(flag){
                    String clearPath =  removeFile.getPath();
                    // 清空 该目录下的文件
                    DeleteDirTest.deleteDir(clearPath);
                }
                /*// 查询数据库
                List<VideoFile> been =  videoFileDaoUtils.queryAllVideoFile();
                // 显示数据
                if(been != null && been.size() > 0){
                    list = been;
                    onCliakedSort();
                }*/
                deleteFileDialog.dismiss();
            }
        });
    }
    private void setListener() {
        RxBus.getInstance().subscribe(String.class, new io.reactivex.functions.Consumer() {
            @Override
            public void accept(Object o) throws Exception {
                if (o.equals(RxBusUtil.VIDEO_LIST_ITEM_DELETE)){
                    mMyVideoListAdapter.notifyDataSetChanged();
                }
            }
        });
    }
    /**
     * 上传文件
     * @param videoFile
     */
    private void uploadFile(VideoFile videoFile,int p){
        if (!isUpload){
            position=p;
            current_videoFile=videoFile;
            uploadFileRequest.setOnUploadFileListener(onUploadFileListener);
            uploadBean=new UploadBean(current_videoFile,mContext);
            uploadFileRequest.setRequestBody(uploadBean);
        }else {
            // todo 提示 有文件正在上传
            MyToastUtils.ShortToaseShow(mContext,mContext.getString(R.string.file_uploading));

        }
    }
    //上传文件请求监听事件
    UploadFileRequest.OnUploadFileListener onUploadFileListener=new UploadFileRequest.OnUploadFileListener() {
        @Override
        public void success(UploadFileTokenBean uploadFileTokenBean) {
            //上传缩略图
            //上传到云端
            isUpload=true;
            TokenBean=uploadFileTokenBean;
            current_videoFile.setFile_id(TokenBean.getData().getId());
            iVideoListModle.update(current_videoFile,mContext);
            Intent startIntent = new Intent(mContext, UpLoadFileService.class);
            mContext.startService(startIntent);
            mContext.bindService(startIntent,connection,Context.BIND_AUTO_CREATE);
        }

        @Override
        public void fail(String s) {
            MyClientApplication.getMhandler().post(new Runnable() {
                @Override
                public void run() {
                    MyToastUtils.ShortToaseShow(mContext,mContext.getString(R.string.upload_fail));
                }
            });

        }
    };
    //上传文件服务
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            uploadBinder = (UpLoadFileService.UploadBinder) service;
            UpLoadFileService upLoadFileService=uploadBinder.getService();
            upLoadFileService.setGetUploadProgress(new UpLoadFileService.getUploadProgress() {
                @Override
                public void getProgress(int num) {
                    Log.d("upload","Progress:"+num);
                    //上传文件进度回调

                    Message message=new Message();
                    message.arg1=num;
                    handler.sendMessage(message);
                }
                @Override
                public void succcess() {
                    stopLoad();
                }

                @Override
                public void pause() {
                    isUpload=false;
                }

                @Override
                public void stop() {
                    isUpload=false;

                }

            });
            upLoadFileService.startUpload(TokenBean,uploadBean,current_videoFile);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    /**
     * 停止上传
     */
    private void  stopLoad(){
        isUpload=false;
        Intent stopIntent = new Intent(mContext, UpLoadFileService.class);
        mContext.stopService(stopIntent);
        mContext.unbindService(connection);
    }

    @Override
    public void oncleckedBack() {
        mIVideoListView.toFinshPager();
    }

    @Override
    public void onClickedToCulde() {
        mIVideoListView.toCuldePager();
    }

    @Override
    public void onClickedDelectAll() {
        deleteFileDialog = new DeleteFileDialog(mContext,mContext.getString(R.string.delete_all_the_file_of_the_meeting),mContext.getString(R.string.delete_file));
        deleteFileDialog.show();
        deleteFileDialog.setmIDeleteFileDialogListener(new IDeleteFileDialogListener() {
            @Override
            public void cancel() {
                deleteFileDialog.dismiss();
            }
            @Override
            public void confirm() {
                iVideoListModle.deleteVideoFiles(list,mContext);
                list.clear();
                mMyVideoListAdapter.notifyDataSetChanged();
                mMyVideoListAdapter.changeState(2);
                deleteFileDialog.dismiss();
            }
        });

    }

    @Override
    public void onCliakedSort() {
        if(flag){
            Collections.sort(list,new ReverseOrder());
            flag = false;
        }else{
            Collections.sort(list,new VideoFileComparator());
            flag = true;
        }
        mMyVideoListAdapter.addItemDate(list);
    }

    @Override
    public void updateInitDate() {
        list.clear();
        getVideoFile();
    }

    class VideoFileComparator implements Comparator<VideoFile> {
        public int compare(VideoFile o1, VideoFile o2) {
            if (o1.getCreatetime()<o2.getCreatetime()){
                return 1;
            }else {
                return -1;
            }
        }

    }
    class ReverseOrder implements Comparator<VideoFile>{

        @Override
        public int compare(VideoFile videoFile, VideoFile t1) {
            if (videoFile.getCreatetime()<t1.getCreatetime()){
                return -1;
            }else {
                return 1;
            }
        }
    }
}
